package controllers
{
	import flash.external.ExternalInterface;
	import flash.system.Capabilities;
	
	import avmplus.getQualifiedClassName;
	

	/**
	 * 
	 * @author Pamakids-Chita
	 * 
	 */
	public class EventTracer
	{
		public static var VERSION:String = "NOT SURE";
		public static var PLATFORM:String = Capabilities.manufacturer;
		public static var PLAYERTYPE:String = Capabilities.playerType;
		public static var OS:String = Capabilities.os;
		private static var _instance:EventTracer
		public static function  get instance():EventTracer 
		{
			return _instance ||= new EventTracer;
		}
//		public var url:String='http://pamaUserBase.avosapps.com/';
		public var urluserbase:String='http://pamaUserBase.avosapps.com/';
		public var urluserInfo:String='http://pamauserInfo.avosapps.com/';
		public var urlusingTime:String='http://pamausingTime.avosapps.com/';
		public var urlpaintOp:String='http://pamapaintOp.avosapps.com/';
		public var urlpaintCreate:String='http://pamapaintcreate.avosapps.com/';
		public var request:AllRequest;
		/**
		 * 
		 * 
		 */		
		public function EventTracer()
		{
			request = new AllRequest()
			enterPage("mainProgram",0);//进入主程序
		}
		
		private function identify(id:String,obj:Object):void
		{
//			ExternalInterface.call('zhuge.identify',id,obj);
		}
		
		private function track(eventName:String,obj:Object):void
		{
//			ExternalInterface.call('zhuge.track',eventName,obj);
			
			var str:String=eventName+'\n'+JSON.stringify(obj)+'\n';
//			ExternalInterface.call('traceEvent',str);
		}
		
//		public function traceEvent(label:String,target:Object):void
//		{
//			
//		}
		private var currentUserId:String
		/**
		 *登录用户  必须最新调用 
		 * @param user
		 * 
		 */		
		public function loginUser(id:String,user:Object,version:String):void
		{
			VERSION =  version
			currentUserId = id;
			enterPage("loginPage",999)
			sendGet(urluserInfo,'userInit',mergeUserData(mergeObj({loginTime:new Date},user)))
			
//			name,gender.birthday,avatar,email.mobile,qq,weixin,weibo,location
				
			identify(id,user);
			
			trace("EventTracer.loginUser(id, user, version)",PLATFORM);
		}
		private var pageMap:Object={};
		private var pagesStack:Object={};

		/**
		 * 
		 * @param pageName 界面名
		 * @param level	界面级别 1 2 3 4 5 6
		 * @param pid	画id
		 * @param uid	人id
		 * 
		 */		
		public function enterPage(pageName:String,level:int,pid:String=null,uid:String=null):void
		{
			var current:String = pagesStack[level];
			var d:Date = new Date
			var currentTime:uint = d.getTime(); 
			if(current)
			{
//				var time:Date = pageMap[current]['date'] || d;
//				tracePageTime(current,level,time,d,pageMap[current]['other']);
				delete pageMap[current]
			}
			pagesStack[level] = pageName
			var o:Object = pageMap[pageName]={}
			o['date'] = d
			o['other']={}
			o['other']['pic']=pid
			o['other']['uid']=uid
//			currentPaintOps=[];
				
			track("enterPage",{'pageName':pageName,'pageLevel':level,'pid':pid,'uid':uid})
		}
		/**
		 *对页面的操作 
		 * @param type 操作类型名
		 * @param otherId	是不是对他人的操作，如果是 就是他人的id 不然为null  
		 * @param picId		对不上对图片操作  图片id
		 * @param data		其他数据Object
		 * 
		 */		
		public function activePageEvent(type:String,otherId:String=null,picId:String=null,data:Object=null):void
		{
			var obj:Object=mergeUserData(mergePageData(mergeObj({actionType:type,otherUser:otherId,isSelf:(otherId==null?null:currentUserId==otherId),pic:picId},data)))
			sendGet(urluserbase,'userBase',obj);
			track(type,obj)
		}
		private var currentPaintOps:Array=[];
		/**
		 *画画界面专用 
		 * @param type
		 * @param otherData
		 * 
		 */		
		public function drawPaintEvent(type:String,otherData:Object):void
		{
//			sendGet(url,'paintOp',mergeUserData(mergePageData(mergeObj({drawType:type},otherData))))
			currentPaintOps.push(mergeUserData(mergePageData(mergeObj({drawType:type,beginTime:new Date},otherData))));
		}
		public function createPaintEvent(pid:String,otherData:Object):void
		{
			var paintInfo:Object = mergeUserData(mergePageData(mergeObj({paint:pid},otherData)));
			currentPaintOps = currentPaintOps.map(function (item:Object,...args):Object{
				var o:Object={}
				item.paint = pid
				mergeObj(item,paintInfo)
				o.body = item
				o.method = "POST"
				o.path = '/1.1/classes/paintOp'
				return o;
			})
			sendGet(urlpaintCreate,'paintCreate',paintInfo)
			sendGet(urlpaintOp,'paintOp',currentPaintOps)
			
			track('paintCreate',paintInfo)
			track('paintOp',currentPaintOps)
			
			disposeOperation();
		}
		
		public function disposeOperation():void
		{
			currentPaintOps=[];	
		}
		
		private function mergeObj(o1:Object,o2:Object):Object
		{
			if(o2)
				for  (var i:String in o2) 
					if(o2[i])
						o1[i]=o2[i]
			return o1
		}

		private function mergeUserData(data:Object= null):Object
		{
			data.currentUser = currentUserId
			return data
		}
		private function mergePageData(data:Object=null):Object
		{
			data||= {};
			var tempLevelArr:Array = [];
			var tempPageArr:Array = [];
			for  (var i:String in pagesStack) 
			{
				if(data[i])
				{
					throw new Error(i+'属性名 已经被占用了')
				}
				if(i == '0')
					continue;	//这个属性不合并
				data["level"+i] = pagesStack[i];
				tempLevelArr.push("level"+i);
				tempPageArr.push(pagesStack[i])
			}
			data.levelArr = tempLevelArr;
			data.pageArr = tempPageArr;
			return data;
		}
		private function tracePageTime(name:String,level:int,beginTime:Date,endTime:Date,otherData:Object=null):void
		{
			var lastTime:uint = Math.abs(endTime.getTime() - beginTime.getTime())/1000;
			var obj:Object=mergeUserData(mergeObj({pagelevel:level,pageName:name,beginTime:beginTime,endTime:endTime,lastSecond:lastTime},otherData));
			sendGet(urlusingTime,'usingTime',obj);
			track('usingTime',obj)
		}
		
		public function exitPage(name:String,level:int,beginTime:Date,endTime:Date,otherData:Object=null):void
		{
			var lastTime:uint = Math.abs(endTime.getTime() - beginTime.getTime())/1000;
			var obj:Object=mergeUserData(mergeObj({pagelevel:level,pageName:name,beginTime:beginTime,endTime:endTime,lastSecond:lastTime},otherData));
			sendGet(urlusingTime,'usingTime',obj);
			track('usingTime',obj)
		}
		
		private function getDateObj(d:Date):Object
		{
			var newDate:Date =  new Date(d.getTime());
			trace("EventTracer.getDateObj(d)",JSON.stringify(newDate)
			,newDate.getFullYear()+"-"+format(newDate.getUTCMonth()+1)+"-"+format(newDate.getUTCDate())+"T"+format(newDate.getUTCHours())+":"+format(newDate.getUTCMinutes())+":"+format(newDate.getUTCSeconds())+"."+format(newDate.getUTCMilliseconds(),3)+"Z");
			return {
				"__type": "Date",
				"iso": newDate.getFullYear()+"-"+format(newDate.getUTCMonth()+1)+"-"+format(newDate.getUTCDate())+"T"+format(newDate.getUTCHours())+":"+format(newDate.getUTCMinutes())+":"+format(newDate.getUTCSeconds())+"."+format(newDate.getUTCMilliseconds(),3)+"Z"
			}
		}
		private function format(num:uint,length:int=2):String
		{
			var nStr:String = num.toString();
			var len:int = length - nStr.length;
			var result:String="";
			if(len > 0)
				for (var i:int = 0; i < len; i++)
					result+="0"
			result +=nStr;
			return result;
				
			
		}
		/**
		 *退出程序 
		 * 
		 */
		public function exitProgram():void
		{
			tracePageTime(pagesStack[0],0,pageMap[pagesStack[0]].date,new Date);
		}
		/**
		 *退出登录 
		 * 
		 */		
		public function logout():void
		{
			tracePageTime(pagesStack[999],999,pageMap[pagesStack[999]].date,new Date);
		}
		public function sendGet(url:String,path:String,obj:Object):void
		{
			return;
			mapData(obj);
			if(!(obj is Array)&&!obj.currentUser)return 
			var query:String = "?data="+encodeURIComponent(JSON.stringify(obj));
			traceHandle('[GET]',url,path,query)
			
			request.getUrl(url+path+query,traceHandle,traceHandle)
		}
		private var handle:Object={
			'Date':getDateObj
		}
		private function mapData(obj:Object):void
		{
			var arr:Array;
			if(obj is Array)
			{
				arr = obj as Array;
				arr.forEach(function (item:Object,...args):void{
					mapData(item.body)
				})
			}
			else
			for  (var i:String in obj) 
			{
				trace("EventTracer.mapData(obj)",getQualifiedClassName(obj[i]),i,obj[i]);
				obj[i] = (handle[getQualifiedClassName(obj[i])]||function (a:*):*{return a})(obj[i])
				if(obj[i]==null||i=="_id")
					delete obj[i]
			}
			obj.versonStr=  VERSION;
			obj.platformStr = PLATFORM;
			obj.osStr = OS;
			obj.playerTypeStr = PLAYERTYPE;
		}
		public function sendPost(url:String,path:String,obj:Object):void
		{
			mapData(obj);
			if(!obj.currentUser)return 
			traceHandle('[POST]',url,path,JSON.stringify(obj))
			request.postUrl(url+path,obj,traceHandle,traceHandle)

		}
		public function traceHandle(...args):void
		{
			trace("[EventTracer]",args);
			
//			try
//			{
//				UserBehaviorAnalysis.trackEvent('+++leanCloud+++',JSON.stringify(args));
//			} 
//			catch(error:Error) 
//			{
//			}
		}
		
	}
}
